#include "communicatList.h"
#include "ui_communicatList.h"
#include "databasemanager.h"
#include <QIcon>
#include <QMessageBox>
#include <qtoolbutton.h>
#include <QMenu>
#include <QTabBar>
#include <QScrollArea>
#include "add_group.h"
#include "check_chat.h"

communicateList::communicateList(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::communicateList)
{
    ui->setupUi(this);

    // 设置QTabWidget样式表
    ui->tabWidget->setStyleSheet(
        "QTabWidget::tab-bar { alignment: left; }"
        "QTabBar::tab { "
        "min-width: 0; max-width: 0; opacity: 0; padding: 0; "
        "border: none; background: transparent; "
        "}"
        "QTabBar::tab:selected { "
        "min-width: 80px; max-width: 120px; opacity: 1; "
        "padding: 8px; background: #00A0E9; color: white; "
        "border-radius: 4px; "
        "}"
        );

    ui->toolButton_add->setPopupMode(QToolButton::InstantPopup);
    QMenu *menu = new QMenu(this);
    QAction *addGroup = menu->addAction("创建群聊");
    QAction *createFriendAndGroup = menu->addAction("加好友/群");

    check_chat *c_c=new check_chat(nullptr,this->username);
    add_group *a_g=new add_group(nullptr);
    check_chat *cc=c_c->getInstance(nullptr,this->username);
    add_group *ag=a_g->getInstance(nullptr);

    // 连接信号和槽
    connect(createFriendAndGroup, &QAction::triggered, this, [=]{
        cc->set_username(this->username);
        cc->show();
    });
    connect(addGroup, &QAction::triggered, this,[=]{
        ag->show();
    });

    ui->toolButton_add->setMenu(menu);
    connect(ui->toolButton_add,&QToolButton::clicked,[=]{
        menu->exec(ui->toolButton_add->mapToGlobal(QPoint(0,ui->toolButton_add->height())));
    });

    // 假设tabWidget有多个页面，这里以添加两个带滚动功能的页面为例
    // 先创建QScrollArea并设置属性
    for (int i = 0; i < 2; ++i) {
        QScrollArea* scrollArea = new QScrollArea(this);
        scrollArea->setWidgetResizable(true);
        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

        QWidget* pageWidget = new QWidget(this);
        QVBoxLayout* pageLayout = new QVBoxLayout(pageWidget);
        // 这里可以先向pageLayout添加一些初始内容（如果有）
        // 例如：
        // QPushButton* btn = new QPushButton("Button", this);
        // pageLayout->addWidget(btn);

        pageWidget->setLayout(pageLayout);
        scrollArea->setWidget(pageWidget);

        // 将带有滚动区域的页面添加到tabWidget
        ui->tabWidget->addTab(scrollArea, i == 0? "群成员" : "添加申请");
    }

    QWidget *page_3 =new QWidget(this);
    QVBoxLayout *vlayout=new QVBoxLayout(page_3);
    QLabel *picture=new QLabel(page_3);
    picture->setObjectName("my_picture");
    picture->setPixmap(QPixmap(":/chat_rooms_icon/clientlogo.png"));
    picture->setScaledContents(true);//自适应大小
    picture->setFixedSize(100,100);
    vlayout->addWidget(picture);
    qDebug() << "Set objectName:" << picture->objectName();
    QLabel *username =new QLabel(QString("用户名: %1").arg(this->username));
    username->setObjectName("my_username");
    username->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    username->adjustSize();
    QLabel *nickname =new QLabel(QString("昵称: %1").arg(this->nickname));
    nickname->setObjectName("my_nickname");
    nickname->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    nickname->adjustSize();
    vlayout->addWidget(username);
    vlayout->addWidget(nickname);
    page_3->setLayout(vlayout);
    ui->tabWidget->addTab(page_3,"用户信息");

    this->setWindowIcon(QIcon(":/login/QQ.png"));https://pan.baidu.com/s/1tW__mtTfe3yZN6y-JP4pTA
    //设置名称
    this->setWindowTitle("qq 2025");

    // 在添加页面等初始化操作之后，确保QToolBox状态稳定
    ui->tabWidget->setCurrentIndex(0);

    connect(ui->check_pushButton,&QPushButton::clicked,[=]{
        currentIndex=1;
        ui->tabWidget->setCurrentIndex(currentIndex);
        int cnt=0;//循环次数
        bool go=false;
        while(!go&&cnt++<5)
        {
            go=Request();
        }
        if(cnt==6)
        {
            QMessageBox::information(NULL,"提示","网络延迟有问题");
        }
    });
    connect(ui->chat_pushButton,&QPushButton::clicked,[=]{
        currentIndex=0;
        ui->tabWidget->setCurrentIndex(currentIndex);
        Chat();
    });
    connect(ui->person_pushButton,&QPushButton::clicked,[=]{
        currentIndex=2;
        ui->tabWidget->setCurrentIndex(currentIndex);
        PersonMessage();
    });

    connect(ui->tabWidget,&QTabWidget::currentChanged,[=](int index){
        if(index==0)
        {
            ui->tabWidget->widget(2)->setVisible(false);
            ui->tabWidget->widget(1)->setVisible(false);
            ui->tabWidget->widget(0)->setVisible(true);
        }
        else if(index==1)
        {
            ui->tabWidget->widget(2)->setVisible(false);
            ui->tabWidget->widget(0)->setVisible(false);
            ui->tabWidget->widget(1)->setVisible(true);
        }
        else if(index==2)
        {
            ui->tabWidget->widget(2)->setVisible(true);
            ui->tabWidget->widget(0)->setVisible(false);
            ui->tabWidget->widget(1)->setVisible(false);
        }
    });


}

void communicateList::set_baseInformation(const QString& username, const QString& nickname,const QString& path,const QString& last_login_time)
{
    this->username=username;this->nickname=nickname;
    this->avatar_path=path;this->last_login_time=last_login_time;
}

void communicateList::Chat()
{
    QScrollArea* scrollArea = qobject_cast<QScrollArea*>(ui->tabWidget->widget(0));
    QVector<std::tuple<QString,QString,QString>> vec=DatabaseManager::getInstance().query_path(username);

    if(vec!=qvec)
    {
        change_chat=false;
        qvec=vec;
        qDebug()<<"Chat update";
    }
    if(!change_chat)
    {
    change_chat=true;
    while (scrollArea->widget()->layout()->count()) {
        QLayoutItem* item = scrollArea->widget()->layout()->takeAt(0);
        if (item) {
            QWidget* widget = item->widget();
            if (widget) {
                widget->deleteLater();
            }
            delete item;
        }
    }
    QVector<QToolButton*> vector;
    int cnt=qvec.size();
    qDebug()<<"cnt="<<cnt;
    for(int i=0;i<cnt;++i)
    {
        QToolButton *btn=new QToolButton(this);
        btn->setFixedSize(400,200);
        //加载图片
        btn->setIcon(QPixmap(QString("%1").arg(std::get<0>(qvec[i]))));
        qDebug()<<" "<<i<<" "<<std::get<0>(qvec[i]);
        //设置大小
        btn->setIconSize(QSize(60,60));
        //设置网名
        btn->setText(QString("%1").arg(std::get<2>(qvec[i])));
        //透明
        btn->setAutoRaise(true);
        //显示格式
        btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);

        scrollArea->widget()->layout()->addWidget(btn);
        vector.push_back(btn) ;
        isShow.push_back(false);
    }
    for(int i=0;i<cnt;++i)
    {
        connect(vector[i],&QToolButton::clicked,[=](){
            if(isShow[i])
            {
                QMessageBox::warning(this,"警告","该聊天已经打开");
                return ;
            }
            isShow[i]=true;
            Widget *widget=new Widget(nullptr,this->username,this->last_login_time);
            widget->set_basement(std::get<1>(vec[i]),std::get<2>(vec[i]));
            widget->setWindowIcon(vector[i]->icon());
            widget->setWindowTitle(vector[i]->text());
            widget->show();
            //connect第三个参数
            connect(widget,&Widget::closeWidget,this,[=](){
                isShow[i]=false;
            });
        });
    }
    }
}

bool communicateList::Request()
{
    QScrollArea* scrollArea = qobject_cast<QScrollArea*>(ui->tabWidget->widget(1));
    QVector<std::tuple<QString,QString,QString,int>> vec=DatabaseManager::getInstance().query_request(username);
    int size_head=vec.size();
    vec.append(DatabaseManager::getInstance().query_send_request(this->username));
    if(vec!=request)
    {
        change_request=false;
        request=vec;
        qDebug()<<"Request update";
    }
    if(!change_request)
    {
        change_request=true;
        while (scrollArea->widget()->layout()->count()) {
            QLayoutItem* item = scrollArea->widget()->layout()->takeAt(0);
            if (item) {
                QWidget* widget = item->widget();
                if (widget) {
                    widget->deleteLater();
                }
                delete item;
            }
        }
        QVector<QWidget*> vector;
        int cnt=request.size();
        qDebug()<<"cnt="<<cnt;
        for(int i=0;i<cnt;++i)
        {
            QWidget *widget=new QWidget(this);
            widget->setFixedSize(350,100);
            QHBoxLayout *hlayout=new QHBoxLayout(widget);
            QLabel *picture=new QLabel(widget);
            picture->setPixmap(QPixmap(std::get<0>(request[i])));
            picture->setScaledContents(true);//自适应大小
            picture->setFixedSize(100,100);
            hlayout->addWidget(picture);
            QLabel *text_label=new QLabel(QString("%1 %2").arg(std::get<1>(request[i])).arg(std::get<2>(request[i])),widget);
            hlayout->addWidget(text_label);
            if(i<size_head){
                if(std::get<3>(request[i])==1)
                {
                    QPushButton* button_1=new QPushButton("同意");
                    QPushButton* button_2=new QPushButton("不同意");
                    connect(button_1,&QPushButton::clicked,[=]{
                        DatabaseManager::getInstance().insert_request_or_member(1,0,std::get<1>(request[i]),this->username,1);
                        // change_chat=false;
                        Request();
                        return false;
                    });
                    connect(button_2,&QPushButton::clicked,[=]{
                         DatabaseManager::getInstance().insert_request_or_member(1,0,std::get<1>(request[i]),this->username,2);
                        Request();
                        return false;
                    });
                    hlayout->addWidget(button_1);
                    hlayout->addWidget(button_2);
                }
                else if(std::get<3>(request[i])>1){
                    QLabel *res_label=new QLabel(widget);
                    if(std::get<3>(request[i])==3)
                    {
                        res_label->setText("已不同意");
                    }else res_label->setText("已同意");
                    hlayout->addWidget(res_label);
                }
            }else{
                if(std::get<3>(request[i])==1)
                {
                    QLabel *res_label=new QLabel(widget);
                    res_label->setText("已申请");
                    hlayout->addWidget(res_label);
                }
                else if(std::get<3>(request[i])>1){
                    QLabel *res_label=new QLabel(widget);
                    if(std::get<3>(request[i])==3)
                    {
                        res_label->setText("对方已不同意");
                    }else res_label->setText("对方已同意");
                    hlayout->addWidget(res_label);
                }
            }
            widget->setLayout(hlayout);
            scrollArea->widget()->layout()->addWidget(widget);
            vector.push_back(widget);
        }

    }
    return true;
}

void communicateList::PersonMessage()
{
    std::tuple<QString,QString,QString> vec=DatabaseManager::getInstance().query_login(this->username);
    if(std::get<0>(vec)!=this->nickname||std::get<1>(vec)!=this->avatar_path)
    {
        change_msg=false;
        this->avatar_path=std::get<1>(vec);
        this->nickname=std::get<0>(vec);
    }
    if(!change_msg){
    change_msg=true;
        QWidget* page_3 = ui->tabWidget->widget(2);
        if (!page_3) {
            qDebug() << "未找到 page_3 页面";
            return;
        }
    QLabel *picture=page_3->findChild<QLabel*>("my_picture");
    QLabel *username=page_3->findChild<QLabel*>("my_username");
    QLabel *nickname=page_3->findChild<QLabel*>("my_nickname");

    if (picture) {
        picture->setPixmap(QPixmap(this->avatar_path));
    } else {
        qDebug() << "未找到名为 my_picture 的 QLabel 控件";
    };
    username->setText(this->username);
    nickname->setText(this->nickname);
    }
}

communicateList::~communicateList()
{
    delete ui;
}

void communicateList::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton reply=QMessageBox::question(
        this,"退出","是否确认退出",
        QMessageBox::Yes|QMessageBox::No);
    if(reply==QMessageBox::Yes)
    {
        if(DatabaseManager::getInstance().CloseUserStatus(this->username))
        {
            bool res=DatabaseManager::getInstance().close_login(this->username);
            if(res){
                qDebug()<<"退出成功";
                event->accept();
            }
            else {
                QMessageBox::critical(this,"错误","服务端有未发送正确回应");
                event->ignore();
            }
        }else {
            QMessageBox::critical(this,"错误","更新用户状态失败");
            event->ignore();
        }
    }else {
        event->ignore();
    }
}
